/*
 * $Id: UserLogService.java 42 2013-04-17 15:33:59Z gabakyan $
 * $Author: gabakyan $
 * $Revision: 42 $
 * $Date: 2013-04-17 15:33:59 +0000 (Wed, 17 Apr 2013) $
 *
 * Copyright (c) 2013 Supply Chain Intelligence (SCI), Inc.
 * http://www.scintelligence.com/, Email: info@scintelligence.com
 * All rights reserved.
 *
 * This file is part of Logistics Map.
 *
 * Logistics Map is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * Logistics Map is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Logistics Map.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.sci.logisticsmap.service;

import com.sci.logisticsmap.data.model.UserModel;
import com.sci.logisticsmap.data.model.UserLogModel;
import com.sci.logisticsmap.data.repository.UserLogRepository;
import com.sci.logisticsmap.data.repository.UserRepository;
import com.sci.logisticsmap.data.support.sorting.UserLogModelSorting;
import com.sci.logisticsmap.service.model.UserLogDTModel;
import com.sci.logisticsmap.service.support.ServiceException;
import com.sci.logisticsmap.service.model.SessionUserDTModel;
import com.sci.logisticsmap.support.Constants;
import com.sci.logisticsmap.support.Page;
import com.sci.logisticsmap.support.Utilities;
import com.sci.logisticsmap.support.model.UserLogType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * The Service for working with User log model.
 *
 * @author gabakyan@gmail.com (Last modified by $Author: gabakyan $)
 * @version $Revision: 42 $
 */
@Service
@Transactional
public class UserLogService extends BaseService {
    /**
     * The user repository.
     */
    @Autowired
    private UserRepository userRepository;
    /**
     * The user log repository.
     */
    @Autowired
    private UserLogRepository userLogRepository;

    /**
     * Adds the {@link UserLogType#SIGN_IN} user log entry.
     *
     * @param sessionUser The session user.
     * @param sessionId The session id.
     */
    public void addSignIn(SessionUserDTModel sessionUser, String sessionId) {
        add(UserLogType.SIGN_IN, sessionUser, sessionId);
    }

    /**
     * Adds the {@link UserLogType#SIGN_OUT} user log entry.
     *
     * @param sessionUser The session user.
     * @param sessionId The session id.
     */
    public void addSignOut(SessionUserDTModel sessionUser, String sessionId) {
        add(UserLogType.SIGN_OUT, sessionUser, sessionId);
    }

    /**
     * Adds the {@link UserLogType#SIGN_UP} user log entry.
     *
     * @param sessionUser The session user.
     */
    public void addSignUp(SessionUserDTModel sessionUser) {
        add(UserLogType.SIGN_UP, sessionUser, null);
    }

    /**
     * Adds the {@link UserLogType#SESSION_DESTROYED} user log entry.
     *
     * @param sessionId The session id.
     */
    public void addSessionDestroyed(String sessionId) {
        logger.debug("addSessionDestroyed: trying to get the user log of the type \"sign in\" by the sessionId = {}", sessionId);
        UserLogModel userLog = userLogRepository.findBySessionIdAndType(sessionId, UserLogType.SIGN_IN);
        if (userLog != null) {
            logger.debug("addSessionDestroyed: user log = {}", userLog);

            if (userLog.getUser() != null) {
                UserModel user = userLog.getUser();
                add(UserLogType.SESSION_DESTROYED, user, sessionId);
            } else {
                logger.debug("addSessionDestroyed: unexpected state, the user is null, do nothing");
            }
        } else {
            logger.debug("addSessionDestroyed: user log is null, not signed in user, do nothing");
        }
    }

    /**
     * Retrieves the user log models.
     *
     * @param page The page.
     *
     * @return The user log models.
     */
    public Page<UserLogDTModel> getDTModels(int page) {
        return getDTModels(page, Constants.DEFAULT_PAGE_SIZE, null);
    }

    /**
     * Retrieves the user log models.
     *
     * @param page The page.
     * @param pageSize The page size.
     *
     * @return The user log models.
     */
    public Page<UserLogDTModel> getDTModels(int page, int pageSize) {
        return getDTModels(page, pageSize, null);
    }

    /**
     * Retrieves the user log models.
     *
     * @param page The page.
     * @param keyword The keyword.
     *
     * @return The user log models.
     */
    public Page<UserLogDTModel> getDTModels(int page, String keyword) {
        return getDTModels(page, Constants.DEFAULT_PAGE_SIZE, null);
    }

    /**
     * Retrieves the user log models.
     *
     * @param page The page.
     * @param pageSize The page size.
     * @param keyword The keyword.
     * 
     * @return The user log models.
     */
    public Page<UserLogDTModel> getDTModels(int page, int pageSize, String keyword) {
        try {
            Page<UserLogModel> userLogPage = userLogRepository.findAll(page, pageSize, UserLogModelSorting.BY_CREATION_DATE_DESC);
            if (userLogPage != null) {
                return conversionUtilities.convert(userLogPage, UserLogDTModel.class);
            }
            return null;
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Adds the user log entry.
     *
     * @param type The user log entry type.
     * @param user The user.
     * @param sessionId The session id.
     */
    private void add(UserLogType type, UserModel user, String sessionId) {
        try {
            Date nowGMTDate = Utilities.getGMTDate();

            UserLogModel userLog = new UserLogModel(type, user, sessionId, nowGMTDate);

            userLogRepository.save(userLog);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }

    /**
     * Adds the user log entry.
     *
     * @param type The user log entry type.
     * @param sessionUser The session user.
     * @param sessionId The session id.
     */
    private void add(UserLogType type, SessionUserDTModel sessionUser, String sessionId) {
        try {
            UserModel user = null;
            if (sessionUser != null) {
                user = userRepository.findOne(sessionUser.getUsername());
            }
            add(type, user, sessionId);
        } catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}
